<template>
  <div ref="vantaRef" class="login-container medical-system">
    <div class="login-form-container">
      <el-card class="login-card glass-effect scale-in" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="logo-section">
              <div class="logo-glow">
                <img
                  src="https://picsum.photos/60"
                  alt="系统Logo"
                  class="login-logo"
                />
              </div>
            </div>
            <h2 class="login-title">溃疡性结肠炎智能评分系统</h2>
            <p class="login-subtitle">EndoSight-UC 医生工作站</p>
          </div>
        </template>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          size="large"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入工号"
              prefix-icon="User"
              clearable
              :disabled="loading"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              :disabled="loading"
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="login-button"
              :loading="loading"
              @click="handleLogin"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'

// 动态导入Vanta.js - 避免首屏加载THREE.js
const loadVanta = async () => {
  const [THREE, WAVES] = await Promise.all([
    import('three'),
    import('vanta/src/vanta.waves')
  ])
  return { THREE: THREE.default, WAVES: WAVES.default }
}

interface LoginForm {
  username: string
  password: string
}

const store = useStore()
const router = useRouter()
const route = useRoute()

// Vanta背景引用
const vantaRef = ref<HTMLElement>()
let vantaEffect: any = null

// 表单引用
const loginFormRef = ref<InstanceType<typeof ElForm>>()

// 加载状态
const loading = ref(false)

// 登录表单数据
const loginForm = reactive<LoginForm>({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入工号', trigger: 'blur' },
    { min: 3, max: 20, message: '工号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true

    await store.dispatch('auth/login', {
      username: loginForm.username,
      password: loginForm.password
    })

    ElMessage.success('登录成功')

    // 获取重定向路径
    const redirectPath = route.query.redirect as string || '/scoring/new'
    router.push(redirectPath)
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}

// 初始化Vanta背景
const initVanta = async () => {
  if (!vantaRef.value) return

  try {
    const { THREE, WAVES } = await loadVanta()

    vantaEffect = WAVES({
      el: vantaRef.value,
      THREE: THREE,
      mouseControls: true,
      touchControls: true,
      gyroControls: false,
      minHeight: 200.00,
      minWidth: 200.00,
      scale: 1.00,
      scaleMobile: 1.00,
      color: 0x0077ff,
      color2: 0x5856d6,
      backgroundColor: 0x1c1c1e,
      speed: 1.5,
      zoom: 0.8
    })
  } catch (error) {
    console.warn('Vanta背景加载失败，使用静态背景', error)
  }
}

// 清理Vanta背景
const destroyVanta = () => {
  if (vantaEffect) {
    vantaEffect.destroy()
    vantaEffect = null
  }
}

onMounted(() => {
  // 延迟加载Vanta，避免阻塞登录交互
  setTimeout(() => {
    initVanta()
  }, 100)
})

onBeforeUnmount(() => {
  destroyVanta()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-form-container {
  width: 100%;
  max-width: 400px;
  padding: 20px;
  z-index: 10;
  position: relative;
}

.login-card {
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(20px) saturate(180%);
  -webkit-backdrop-filter: blur(20px) saturate(180%);
  background-color: rgba(255, 255, 255, 0.1);
  box-shadow: 0 25px 45px -12px rgba(0, 0, 0, 0.25);
}

.card-header {
  text-align: center;
  margin-bottom: 20px;
}

.logo-section {
  margin-bottom: 16px;
}

.logo-glow {
  display: inline-block;
  border-radius: 16px;
  padding: 8px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px -4px rgba(0, 0, 0, 0.3);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.logo-glow:hover {
  transform: scale(1.05);
}

.login-logo {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: block;
}

.login-title {
  font-size: 24px;
  font-weight: 700;
  color: #ffffff;
  margin: 16px 0 8px 0;
  letter-spacing: 0.5px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.login-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  font-weight: 500;
}

.login-form {
  padding: 0 8px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: linear-gradient(135deg, #0077ff 0%, #5856d6 100%);
  border: none;
  box-shadow: 0 10px 25px -5px rgba(0, 119, 255, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 15px 35px -5px rgba(0, 119, 255, 0.6);
}

.login-button:active {
  transform: translateY(0);
}

/* Element Plus 深色模式定制 */
:deep(.el-card__body) {
  padding: 32px 24px;
}

:deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: none;
  border-radius: 12px;
  height: 48px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.el-input__wrapper:hover) {
  background-color: rgba(255, 255, 255, 0.15);
  border-color: rgba(255, 255, 255, 0.3);
}

:deep(.el-input__wrapper.is-focus) {
  background-color: rgba(255, 255, 255, 0.2);
  border-color: #0077ff;
  box-shadow: 0 0 0 3px rgba(0, 119, 255, 0.1);
}

:deep(.el-input__inner) {
  color: #ffffff;
  font-size: 16px;
  height: 46px;
  line-height: 46px;
}

:deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.el-input__prefix-inner) {
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-form-item__error) {
  color: #ff6b6b;
  font-size: 12px;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-form-container {
    max-width: 320px;
    padding: 16px;
  }

  .login-card {
    border-radius: 16px;
  }

  .login-title {
    font-size: 20px;
  }

  .login-subtitle {
    font-size: 13px;
  }
}
</style>